package com.ant.business.system.service.impl;

import com.ant.business.system.entity.Module;
import com.ant.business.system.mapper.ModuleDao;
import com.ant.business.system.service.ModuleService;
import com.ant.business.system.vo.UserVo;
import com.ant.common.constant.SystemConstant;
import com.ant.common.exceptions.BusinessException;
import com.ant.common.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 模块管理Service实现类
 *
 * @author
 * @description
 * @create 2021-03-22 14:25:56
 */
@Service("moduleService")
@Transactional(rollbackFor = Throwable.class)
public class ModuleServiceImpl extends ServiceImpl<ModuleDao, Module> implements ModuleService {

    private final ModuleDao moduleDao;

    public ModuleServiceImpl(ModuleDao moduleDao) {
        this.moduleDao = moduleDao;
    }

    /**
     * 分页查询列表
     *
     * @param page  页数
     * @param limit 条数
     * @return PageInfo
     */
    @Override
    public PageInfo<Module> getList(int page, int limit, FastMap param) {
        QueryWrapper<Module> wrapper = new QueryWrapper<>();

        if (StringUtil.isNotEmpty(param.getString("moduleName"))) {
            wrapper.like("module_name", param.getString("moduleName"));
        }

        PageHelper.startPage(page, limit);
        List<Module> list = moduleDao.selectList(wrapper);
        PageInfo<Module> pageInfo = new PageInfo<>(list);

        List<Module> newList = pageInfo.getList().stream().peek(x -> {
            Module parentModule = this.getById(x.getParentId());
            if (parentModule != null) x.setParentName(parentModule.getName());
        }).collect(Collectors.toList());

        pageInfo.setList(newList);

        return pageInfo;
    }

    /**
     * 检查模块信息
     *
     * @param module module
     * @return boolean
     */
    private boolean checkInfoExists(Module module, Integer moduleId) {
        QueryWrapper<Module> wrapper = new QueryWrapper<Module>().eq("module_name", module.getName());

        if (IntegerUtil.isEmpty(moduleId)) {
            wrapper.ne("module_id", moduleId);
        }
        List<Module> moduleList = this.list(wrapper);
        return moduleList.size() != 0;
    }

    /**
     * 新增信息
     *
     * @param module module
     */
    @Override
    @SneakyThrows
    public void saveOne(Module module) {
        if (checkInfoExists(module, 0)) {
            throw new BusinessException("模块名称不能重复");
        }
        LocalBeanUtil.setLoginUserInfo(module);
        module.setDeleteFlag(SystemConstant.DELETE_STATUS.UN_DELETE.getCode());
        int count = moduleDao.insert(module);
        if (count != 1) {
            throw new BusinessException("保存失败");
        }
    }

    /**
     * 更新信息
     *
     * @param module module
     */
    @Override
    @SneakyThrows
    public void update(Module module) {
        if (checkInfoExists(module, module.getId())) {
            throw new BusinessException("模块名称不能重复");
        }

        LocalBeanUtil.updateLoginUserInfo(module);
        int count = moduleDao.updateById(module);
        if (count != 1) {
            throw new BusinessException("更新失败");
        }
    }

    /**
     * 删除信息
     *
     * @param primaryKey id
     */
    @Override
    @SneakyThrows
    public void delete(String primaryKey) {
        Module module = moduleDao.selectById(primaryKey);

        Module newModule = new Module();
        newModule.setId(Integer.valueOf(primaryKey));
        newModule.setDeleteFlag(SystemConstant.DELETE_STATUS.DELETED.getCode());
        newModule.setName(module.getName() + "_" + IdWorker.get32UUID());
        LocalBeanUtil.updateLoginUserInfo(newModule);

        int count = moduleDao.updateById(newModule);
        if (count != 1) {
            throw new BusinessException("删除失败");
        }
    }

    /**
     * 根据登录用户查询模块信息
     *
     * @param userVo 用户VO类
     * @return List<Module>
     */
    @Override
    public List<Module> getModuleListByUser(UserVo userVo) {
        int userType = userVo.getUserType();
        QueryWrapper<Module> wrapper = new QueryWrapper<>();
        wrapper.eq("delete_flag", SystemConstant.DELETE_STATUS.UN_DELETE.getCode());

        if (userType == SystemConstant.USER_TYPE.PLATFORM_ADMIN.getCode()) {
            //平台级管理员
            wrapper.eq("type", SystemConstant.MODULE_TYPE.PLATFORM_MODULE.getCode());
            return this.list(wrapper);
        } else if (userType == SystemConstant.USER_TYPE.UNIT_ADMIN.getCode()) {
            //商户管理员
            wrapper.eq("type", SystemConstant.MODULE_TYPE.UNIT_MODULE.getCode());
            return this.list(wrapper);
        } else {
            return moduleDao.getModuleListByUserId(userVo.getUserId(), userVo.getUnitId());
        }
    }

    /**
     * 查询所有商户模块
     *
     * @return List<Module>
     */
    @Override
    public List<Module> getAllModule() {
        return this.list(new QueryWrapper<Module>().eq("type", SystemConstant.MODULE_TYPE.UNIT_MODULE.getCode()));
    }

    /**
     * 该角色本身有的商户模块
     *
     * @param roleId roleId
     * @return List<Module>
     */
    @Override
    public List<Module> getModuleListByRoleId(String roleId) {
        UserVo user = UserThreadLocal.getUser();
        return moduleDao.getModuleListByRoleId(Integer.valueOf(roleId), user.getUnitId());
    }
}
